package cn.hd01.weixin;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.hd01.common.BaseConstant.AuditStatus;
import cn.hd01.common.BaseConstant.CustomerType;
import cn.hd01.common.BaseConstant.IsBalance;
import cn.hd01.common.BaseConstant.RebateSummaryType;
import cn.hd01.common.IntegrationRuleCode;
import cn.hd01.repository.entity.COrder;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.Dictionary;
import cn.hd01.repository.entity.DistributorLevel;
import cn.hd01.repository.entity.HotRecommend;
import cn.hd01.repository.entity.Integration;
import cn.hd01.repository.entity.IntegrationRule;
import cn.hd01.repository.entity.IntegrationRuleBook;
import cn.hd01.repository.entity.MyCustomer;
import cn.hd01.repository.entity.RebateBook;
import cn.hd01.repository.entity.RebateSummary;
import cn.hd01.repository.entity.Servant;
import cn.hd01.repository.entity.WXApp;
import cn.hd01.repository.entity.WXOauth;
import cn.hd01.service.BookRecordService;
import cn.hd01.service.COrderService;
import cn.hd01.service.CustomerService;
import cn.hd01.service.DictionaryService;
import cn.hd01.service.DistributorDetailsService;
import cn.hd01.service.DistributorLevelService;
import cn.hd01.service.HotRecommendService;
import cn.hd01.service.IntegrationRuleBookService;
import cn.hd01.service.IntegrationRuleService;
import cn.hd01.service.IntegrationService;
import cn.hd01.service.RebateBookService;
import cn.hd01.service.RebateSummaryService;
import cn.hd01.service.ServantService;
import cn.hd01.service.WXAppService;
import cn.hd01.util.CommonUtil;
import cn.hd01.util.DictionaryType;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebException;
import cn.hd01.web.util.WebHelper;
import cn.hd01.weixin.model.Result;
import cn.hd01.weixin.util.QRCodeUtil;

import com.google.zxing.WriterException;

@Controller
@RequestMapping("/weixin/customer")
@Auth(AuthType.WECHAT)
public class WXCustomer {
	private Logger logger = LoggerFactory.getLogger(WXCustomer.class);

	@Autowired
	private CustomerService customerService;

	@Autowired
	private WXAppService wxAppService;
	
	@Autowired
	private DistributorLevelService levelService;

	@Autowired
	private ServantService servantService;
	
	@Autowired
	private COrderService cOrderService;
	
	@Autowired
	private RebateSummaryService summaryService;
	
	@Autowired
	private IntegrationRuleBookService integrationRuleBookService;
	
	@Autowired
	private IntegrationService integrationService;
	
	@Autowired
	private RebateSummaryService rebateSummaryService;
	
	@Autowired
	private RebateBookService rebateBookService;
	
	@Autowired
	private BookRecordService bookRecordService;
	
	@Autowired
	private DistributorDetailsService distributorDetailsService;

	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private HotRecommendService hotRecommendService;
	
	@Autowired
	private IntegrationRuleService integrationRuleService;
	
	@Autowired
	private COrderService corderService;
	
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(path = "", method = RequestMethod.GET)
	public String index(Model m) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (customer == null) {
			return "redirect:/weixin/login";
		}

		m.addAttribute("customer", customer);
		
		if (customer.getLevelId() != null) {
			m.addAttribute("level", levelService.findOne(customer.getLevelId()));
		}
		
		if (CustomerType.CUSTOMER.equals(customer.getType())) {
			int count = integrationRuleBookService.countTodayRule(customer.getId(), IntegrationRuleCode.SIGN_INTEGRATION.getRuleCode());
			m.addAttribute("displaySign", count == 0);
			int bookCount = bookRecordService.countRecord(customer.getId());
			m.addAttribute("bookCount", bookCount);
			COrder order = new COrder();
			order.setCustomerId(customer.getId());
			List<COrder> list = cOrderService.findAll(order);
			BigDecimal amount = BigDecimal.ZERO;
			for(COrder o : list){
				amount = amount.add(o.getAmount());
			}
			Integration myIntegrate = integrationService.findByCustomerId(customer.getId());
			BigDecimal integrate = myIntegrate.getIntegration();
			List<Dictionary> dictList = dictionaryService.findByType(DictionaryType.STAR_LEVEL);
			String startName ="";
			if(CollectionUtils.isEmpty(dictList)){
				
			}else{
				for (Dictionary dictionary : dictList) {
					String value = dictionary.getValue();
					String vues [] =value.split("-");
					if(vues.length > 1){
						BigDecimal start = new BigDecimal(vues[0]);
						BigDecimal end = new BigDecimal(vues[1]);
						if(start.compareTo(integrate) != 1 && integrate.compareTo(end) != 1){//小于等于
							startName = dictionary.getName();
							break;
						}else{
							continue;
						}
					}else{
						//最后一个
						startName = dictionary.getName();
						break;
					}
				}
			}
			Pageable pageable = new PageRequest(0, 2);
			Page<HotRecommend> page = hotRecommendService.findAll(pageable);
			
			m.addAttribute("hotRecommendList", page.getContent());
			m.addAttribute("startName", startName);
			m.addAttribute("myIntegrate", myIntegrate);
			m.addAttribute("amount", amount);
			return "weixin/agent/me";
		}
		
		customer.setDistributorDetails(distributorDetailsService.findByDistributorId(customer.getId()));
		int waitBalanceCount = cOrderService.countByIsBalanceAndDistributorId(IsBalance.BALANCE_WAIT, customer.getId());
		m.addAttribute("waitBalanceCount", waitBalanceCount);
		
		RebateSummary summary = summaryService.findByRefIdAndType(customer.getId(), RebateSummaryType.DISTRIBUTOR);
		String allWithdrawRebate = "0";
		String allRebate = "0";
		if (summary != null) {
			allWithdrawRebate = summary.getAllWithdrawRebate().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
			allRebate = summary.getAllRebate().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
		}
		m.addAttribute("allRebate", allRebate);
		m.addAttribute("allWithdrawRebate", allWithdrawRebate);
		return "weixin/supplier/me";
	}

	@RequestMapping(path = "/qr/{type}", method = RequestMethod.GET)
	public String toqr(Model m, @PathVariable Integer type) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("name", customer.getName());
		m.addAttribute("type", type);
		return "weixin/supplier/qr";
	}

	@RequestMapping(path = "/agent", method = RequestMethod.GET)
	public String toAgent(Model m) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		List<Object[]> list = corderService.findRecommKvalue(customer.getId());
		BigDecimal todayKValue = BigDecimal.ZERO;
		BigDecimal balanceKValue = BigDecimal.ZERO;
		BigDecimal unBalanceKValue = BigDecimal.ZERO;
		if(!CollectionUtils.isEmpty(list)){
			todayKValue = list.get(0)[0] == null ? BigDecimal.ZERO : (BigDecimal) list.get(0)[0];
			balanceKValue = list.get(0)[1] == null ? BigDecimal.ZERO : (BigDecimal) list.get(0)[1];
			unBalanceKValue = list.get(0)[2] == null ? BigDecimal.ZERO : (BigDecimal) list.get(0)[2];
		}
		m.addAttribute("allKValue", balanceKValue.add(unBalanceKValue).intValue());
		m.addAttribute("todayKValue", todayKValue.intValue());
		m.addAttribute("balanceKValue", balanceKValue.intValue());
		m.addAttribute("unBalanceKValue", unBalanceKValue.intValue());
		
		return "weixin/supplier/agent";
	}

	@ResponseBody
	@RequestMapping(path = "/agentlist", method = RequestMethod.GET)
	public Page<Object> recommend(@PageableDefault Pageable pageable) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		//return customerService.findRecommendCustomer(customer.getId(), pageable);
		return rebateBookService.findAgent(customer.getId(), pageable);
	}
	
	@RequestMapping(path = "/toaddagent", method = RequestMethod.GET)
	public String toAddAgent() {
		return "weixin/supplier/addagent";
	}
	
	@RequestMapping(path = "/toKValue", method = RequestMethod.GET)
	public String toKValue(Model m, String beginDate, String endDate) {
		Customer distributor = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		Integer id = distributor.getId();
		m.addAttribute("beginDate", beginDate);
		m.addAttribute("endDate", endDate);
		m.addAttribute("todayKValue", cOrderService.findKValue(id, null, null, SDF.format(new Date()) , null).intValue());//rebateSummaryService.findSummary(id, RebateSummaryType.DISTRIBUTOR, null, null, new Date()).intValue());
		m.addAttribute("allKValue", cOrderService.findKValue(id, null, null, null, null).intValue());///rebateSummaryService.findSummary(id, RebateSummaryType.DISTRIBUTOR, beginDate, endDate, null).intValue());
		m.addAttribute("balanceKValue", cOrderService.findKValue(id, beginDate, endDate, null, IsBalance.BALANCE_DOWN).intValue());
		m.addAttribute("unBalanceKValue", cOrderService.findKValue(id, beginDate, endDate, null, IsBalance.BALANCE_WAIT).intValue());
		m.addAttribute("distributorId", id);
		return "weixin/supplier/kValue";
	}

	@ResponseBody
	@RequestMapping(path = "/addagent", method = RequestMethod.POST)
	public Result addAgent(String name, String phoneNo) {
		Customer old = customerService.findByPhoneNo(phoneNo);
		if (old != null) {
			return new Result(false, "手机号已经存在");
		}

		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		Customer agent = new Customer();
		agent.setName(name);
		agent.setPhoneNo(phoneNo);
		agent.setType(CustomerType.CUSTOMER);
		agent.setActivationStatus(false);
		agent.setRecommendDistributorId(customer.getId());
		customerService.save(agent);
		return new Result();
	}

	@ResponseBody
	@RequestMapping(path = "/qrimg/{type}", method = RequestMethod.GET)
	public void qrSupplier(@PathVariable Integer type, HttpServletResponse response) {
		try {
			response.setContentType("image/png");
			QRCodeUtil.writeToStream(getUrl(type), response.getOutputStream());
		} catch (WriterException | IOException e) {
			throw new WebException(HttpStatus.BAD_GATEWAY, e);
		}
	}

	@RequestMapping(path = "/agentlink/{type}", method = RequestMethod.GET)
	public String toRegister(Model m, @PathVariable Integer type) {
		m.addAttribute("url", getUrl(type));
		return "weixin/supplier/agentlink";
	}

	@RequestMapping(path = "/registe/{type}", method = RequestMethod.GET)
	public String toRegister(Model m, @PathVariable String type, @RequestParam(required = false) Integer from) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (customer != null && customer.getActivationStatus()) {
			return "redirect:/weixin/customer";
		}

		if (from != null && customerService.exists(from)) {
			m.addAttribute("from", from);
		}

		m.addAttribute("type", type);
		return "weixin/register";
	}

	@ResponseBody
	@RequestMapping(path = "/registe", method = RequestMethod.POST)
	public Result register(Customer customer, Integer recommendId, String verifyCode) {
		String code = WebHelper.sessionAttr("code", String.class);
		if (code == null) {
			return new Result(false, "请先获取验证码");
		}

		if (verifyCode == null || !verifyCode.equals(code)) {
			WebHelper.session().removeAttribute("code");
			return new Result(false, "验证码错误");
		}

		WXOauth oauth = WebHelper.currentWXOauth();
		Customer old = customerService.findByPhoneNo(customer.getPhoneNo());
		if (old != null) {
			customer.setId(old.getId());
		}
		
		if(recommendId != null){
			Customer recommUser = customerService.findOne(recommendId);
			if(recommUser != null){
				String recommendName = recommUser.getName();
				String recommendPhoneNo = recommUser.getPhoneNo();
				if(CustomerType.CUSTOMER.equals(recommUser.getType())){
					customer.setRecommendCustomerId(recommendId);
					customer.setRecommendDistributorName(recommendName);
					customer.setRecommendCustomerPhoneNo(recommendPhoneNo);
					customer.setRecommendDistributorId(recommUser.getRecommendDistributorId());
					customer.setRecommendDistributorName(recommUser.getRecommendDistributorName());
					customer.setRecommendDistributorPhoneNo(recommUser.getRecommendDistributorPhoneNo());
					
					//推广积分
					IntegrationRuleBook book = new IntegrationRuleBook();
					book.setCustomerId(recommendId);
					book.setCustomerName(recommendName);
					integrationRuleBookService.save(book, IntegrationRuleCode.RECOMM_CONSUME_INTEGRATION);
					
				}else if(CustomerType.CUSTOMER.equals(recommUser.getType())){
					customer.setRecommendDistributorId(recommendId);
					customer.setRecommendDistributorName(recommendName);
					customer.setRecommendDistributorPhoneNo(recommendPhoneNo);
				}
			}
		}
		

		customer.setAuditStatus(AuditStatus.AUDIT_WAIT);
		customer.setHeadImage(oauth.getHeadimgurl());
		customer.setActivationStatus(true);
		customer.setSex(oauth.getSex() == null ? "0" : oauth.getSex().toString());
		customerService.save(customer);
		return new Result(true, "注册成功");
	}

	private String getUrl(Integer type) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		List<WXApp> list = wxAppService.findAll();
		return WebHelper.basePath() + "/weixin/customer/registe/" + type + "?domain=" + list.get(0).getDomain() + "&from="
				+ customer.getId();
	}

	@RequestMapping(path = "/info", method = RequestMethod.GET)
	public String info(Model m) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("customer", customer);
		return "weixin/info";
	}

	@ResponseBody
	@RequestMapping(path = "/upload", method = RequestMethod.POST)
	public Result upload(MultipartFile file, HttpServletRequest request) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		String basepath = request.getSession().getServletContext().getRealPath("/upload/headimgs");
		File headpath = new File(basepath);
		if (!headpath.exists()) {
			headpath.mkdirs();
		}

		String imgName = customer.getId() + "-" + file.getOriginalFilename();
		try {
			file.transferTo(new File(headpath, imgName));
		} catch (IllegalStateException | IOException e) {
			logger.error(e.getMessage(), e);
			return new Result(false, "头像上传失败");
		}

		customer.setHeadImage(WebHelper.basePath() + "/upload/headimgs/" + imgName);
		customerService.save(customer);
		return new Result(true, customer.getHeadImage());
	}

	@ResponseBody
	@RequestMapping(path = "/modify", method = RequestMethod.POST)
	public Result modify(Customer customer) {
		Customer old = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		old.setSex(customer.getSex());
		old.setArea(customer.getArea());
		old.setAreaId(customer.getAreaId());
		old.setProvince(customer.getProvince());
		old.setProvinceId(customer.getProvinceId());
		old.setCity(customer.getCity());
		old.setCityId(customer.getCityId());

		customerService.save(old);
		return new Result();
	}

	@RequestMapping(path = "/pwdmodify", method = RequestMethod.GET)
	public String pwdmodify() {
		return "weixin/pwdmodify";
	}

	@ResponseBody
	@RequestMapping(path = "/pwdmodify", method = RequestMethod.POST)
	public Result pwdmodify(String oldpwd, String newpwd) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (!oldpwd.equals(customer.getPassword())) {
			return new Result(false, "旧密码输入错误");
		}

		customer.setPassword(newpwd);
		customerService.save(customer);
		return new Result();
	}

	@RequestMapping(path = "/toapplysupplier", method = RequestMethod.GET)
	public String tosupplier(Model m) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("customer", customer);
		return "weixin/agent/applysupplier";
	}

	@ResponseBody
	@RequestMapping(path = "/applysupplier", method = RequestMethod.GET)
	public Result applytosupplier() {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (CustomerType.DISTRIBUTOR.equals(customer.getType())) {
			return new Result(false, "您已经是渠道商");
		}

		customer.setType(CustomerType.DISTRIBUTOR);
		customer.setAuditStatus(AuditStatus.AUDIT_PASS);
		customer.setUpdateTime(new Date());
		customerService.save(customer);
		return new Result();
	}

	@RequestMapping(path = "/service", method = RequestMethod.GET)
	public String service(Model m) {
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (customer.getServantId() != null) {
			Servant servant = servantService.findOne(customer.getServantId());
				m.addAttribute("phone", "13480901603");
		}
		return "weixin/agent/service";
	}
	
	@RequestMapping(path = "/level", method = RequestMethod.GET)
	public String level(Integer id, Model m) {
		DistributorLevel level = levelService.findOne(id);
		m.addAttribute("level", level);
		return "weixin/supplier/level";
	}
	
	@ResponseBody
	@RequestMapping(path = "/sign", method = RequestMethod.GET)
	public Result sign() {
		Result result = new Result();
		
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		
		if(integrationRuleBookService.countTodayRule(customer.getId(), IntegrationRuleCode.SIGN_INTEGRATION.getRuleCode()) == 0){
			IntegrationRuleBook book = new IntegrationRuleBook();
			book.setCustomerId(customer.getId());
			book.setCustomerName(customer.getName());
			integrationRuleBookService.save(book, IntegrationRuleCode.SIGN_INTEGRATION);
			result.setMsg("签到成功!");
		}else{
			result.setMsg("您今日已签到");
		}
		
		return result;
	}

	@RequestMapping(path = "/beautifulItems", method = RequestMethod.GET)
	public String beautifulItems(Model m) {
		return "weixin/agent/beautifulitems";
	}
	
	@RequestMapping(path = "/myintegrations", method = RequestMethod.GET)
	public String myintegrations() {
		return "weixin/agent/myintegrations";
	}
	
	@RequestMapping(path = "/myCustomer", method = RequestMethod.GET)
	public String myCustomer(Model m) {
		Customer dis = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		m.addAttribute("distributorId", dis.getId());
		m.addAttribute("customerCount", customerService.countCustomer(dis.getId()));
		return "weixin/supplier/myCustomer";
	}
	
	@ResponseBody
	@RequestMapping(path = "/tegrateList", method = RequestMethod.GET)
	public Page<IntegrationRuleBook> tegrateList(@PageableDefault Pageable pageable) throws ParseException {
		Sort sort = new Sort(Direction.DESC, "createTime");
		Pageable pageable2 = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
		
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		IntegrationRuleBook integrationRuleBook = new IntegrationRuleBook();
		integrationRuleBook.setCustomerId(customer.getId());
		Page<IntegrationRuleBook> page = integrationRuleBookService.findAll(integrationRuleBook, pageable2);
		List<IntegrationRuleBook> integrationRuleBookList = page.getContent();
		if(CollectionUtils.isEmpty(integrationRuleBookList)){
			return page;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		for (IntegrationRuleBook book : integrationRuleBookList) {
			String date = format.format(book.getCreateTime());
			book.setIntegraDate(date);
		}
		return page;
	}
	
	@ResponseBody
	@RequestMapping(path = "/findMyCustomer", method = RequestMethod.GET)
	public Page<MyCustomer> findMyCustomer(Pageable pageable){
		Customer customer = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		return customerService.findMyCustomer(customer.getId(), pageable);
	}
	
	@RequestMapping(path = "/integrateRule", method = RequestMethod.GET)
	public String integrateRuleList(Model m) {
		List<IntegrationRule> list = integrationRuleService.findAll();
		m.addAttribute("ruleList", list);
		return "weixin/agent/integrationRule";
	}
	
	@ResponseBody
	@RequestMapping(path = "/integrateRuleList", method = RequestMethod.GET)
	public Page<IntegrationRule> integrateRuleList(@PageableDefault Pageable pageable) throws ParseException {
		Page<IntegrationRule> page = integrationRuleService.findAll(pageable);
		List<IntegrationRule> integrationRuleList = page.getContent();
		if(CollectionUtils.isEmpty(integrationRuleList)){
			return page;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		for (IntegrationRule rule : integrationRuleList) {
			String date = format.format(rule.getCreateTime());
			rule.setIntegraDate(date);
		}
		return page;
	}
}
